package com.skyjing.astools;

import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.net.ConnectivityManager;
import android.net.Network;
import android.net.NetworkRequest;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.PowerManager;
import android.provider.Settings;
import android.view.View;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.annotation.RequiresApi;
import androidx.appcompat.app.AppCompatActivity;
import androidx.databinding.DataBindingUtil;

//import com.skyjing.askit.java.AsDownloadManagerUitls;
//import com.skyjing.askit.java.LogUtils;
import com.skyjing.askit.AsAppFile;
import com.skyjing.askit.AsSpTool;
import com.skyjing.askit.AsToast;
import com.skyjing.askit.java.LogUtils;
import com.skyjing.astools.constant.BrandType;
import com.skyjing.astools.databinding.ActivityMainBinding;

public class TestActivity extends AppCompatActivity implements View.OnClickListener {
    private ActivityMainBinding binding;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        binding = DataBindingUtil.setContentView(this, R.layout.activity_main);
        binding.tvTest.setOnClickListener(this);
        binding.btnDownload.setOnClickListener(this);
        binding.btnDownloadkt.setOnClickListener(this);
        binding.btnDownload.setText("电池白名单");
        binding.btnDownloadkt.setText("系统后台管理");
        AsSpTool.init();
        AsSpTool.init("testSp");
        AsSpTool.put("22", "bbb");
        AsSpTool.put("testSp", "111", "ccc");
        AsAppFile.init();
        AsAppFile.init("测试");
        AsAppFile.write("9527");
        AsAppFile.write("测试", "9918");

//        LogUtils.e("文件操作" , "AsAppFile2.read() = " + AsAppFile.read());
//        LogUtils.e("文件操作" , "AsAppFile2.read(\"测试\") = " + AsAppFile.read("测试"));

//        AsSpStrTools2.get().setFlag()
        initNetConnectState();
    }

    private void initNetConnectState(){
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            ConnectivityManager connManager = (ConnectivityManager) getApplicationContext()
                    .getSystemService(Context.CONNECTIVITY_SERVICE);
            connManager.requestNetwork(new NetworkRequest.Builder().build() ,
                    new ConnectivityManager.NetworkCallback(){
                        @Override
                        public void onAvailable(@NonNull Network network) {
                            super.onAvailable(network);
                            LogUtils.e("网络测试" , "onAvailable");
                        }

                        @Override
                        public void onLost(@NonNull Network network) {
                            super.onLost(network);
                            LogUtils.e("网络测试" , "onLost");
                            AsToast.normal("网络丢失");
                        }
                    });
        }
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.tvTest: {
                AsToast.normal("" + AsSpTool.getString("22") + "   " + AsSpTool.getString("testSp", "111"));
            }
            break;
            case R.id.btnDownload: {
//                AsToast.normal("" + AsSpTool.getString("22") + "   " + AsSpTool.getString("testSp", "111"));
                if (!isIgnoringBatteryOptimizations()) {
                    requestIgnoreBatteryOptimizations();
                }
            }
            break;
            case R.id.btnDownloadkt: {
//                AsToast.normal("" + AsSpTool.getString("22") + "   " + AsSpTool.getString("testSp", "111"));
//                if (isHuawei()){
//                    goHuaweiSetting();
//                }
                switch (isBrand()) {
                    case BrandType.HUAWEI: {
                        goHuaweiSetting();
                    }
                    break;
                    case BrandType.XIAOMI: {
                        goXiaomiSetting();
                    }
                    break;
                    case BrandType.OPPO: {
                        goOPPOSetting();
                    }
                    break;
                    case BrandType.VIVO: {
                        goVIVOSetting();
                    }
                    break;
                    case BrandType.MEIZU: {
                        goMeizuSetting();
                    }
                    break;
                    case BrandType.SAMSUNG: {
                        goSamsungSetting();
                    }
                    break;
                    case BrandType.LETV: {
                        goLetvSetting();
                    }
                    break;
                    case BrandType.SMARTISAN: {
                        goSmartisanSetting();
                    }
                    break;

                }
            }
            break;
        }
    }

    /**
     * 判断我们的应用是否在电池白名单中
     *
     * @return
     */
    @RequiresApi(api = Build.VERSION_CODES.M)
    private boolean isIgnoringBatteryOptimizations() {
        boolean isIgnoring = false;
        PowerManager powerManager = (PowerManager) getSystemService(Context.POWER_SERVICE);
        if (powerManager != null) {
            isIgnoring = powerManager.isIgnoringBatteryOptimizations(getPackageName());
        }
        return isIgnoring;
    }

    /**
     * 通过以下代码申请加入电池白名单
     */
    @RequiresApi(api = Build.VERSION_CODES.M)
    public void requestIgnoreBatteryOptimizations() {
        try {
            Intent intent = new Intent(Settings.ACTION_REQUEST_IGNORE_BATTERY_OPTIMIZATIONS);
            intent.setData(Uri.parse("package:" + getPackageName()));
            startActivity(intent);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /***********************************************************************************************
     *  系统后台管理
     ***********************************************************************************************/
    /**
     * 跳转到指定应用的首页
     */
    private void showActivity(@NonNull String packageName) {
        Intent intent = getPackageManager().getLaunchIntentForPackage(packageName);
        startActivity(intent);
    }

    /**
     * 跳转到指定应用的指定页面
     */
    private void showActivity(@NonNull String packageName, @NonNull String activityDir) {
        Intent intent = new Intent();
        intent.setComponent(new ComponentName(packageName, activityDir));
        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        startActivity(intent);
    }

    /***********************************************************************************************
     * 厂商判断：
     ***********************************************************************************************/

    public String isBrand() {
        if (Build.BRAND == null) {
            return "";
        } else {
            switch (Build.BRAND.toLowerCase()) {
                case "huawei":
                case "honor":
                    return BrandType.HUAWEI;
                case "xiaomi":
                    return BrandType.XIAOMI;
                case "oppo":
                    return BrandType.OPPO;
                case "vivo":
                    return BrandType.VIVO;
                case "meizu":
                    return BrandType.MEIZU;
                case "samsung":
                    return BrandType.SAMSUNG;
                case "letv":
                    return BrandType.LETV;
                case "smartisan":
                    return BrandType.SMARTISAN;
            }
        }
        return "";
    }

    /**
     * 华为
     */
    public boolean isHuawei() {
        if (Build.BRAND == null) {
            return false;
        } else {
            return Build.BRAND.toLowerCase().equals("huawei") || Build.BRAND.toLowerCase().equals("honor");
        }
    }

    /**
     * 跳转华为手机管家的启动管理页
     * 操作步骤：应用启动管理 -> 关闭应用开关 -> 打开允许自启动
     */
    private void goHuaweiSetting() {
        try {
            showActivity("com.huawei.systemmanager",
                    "com.huawei.systemmanager.startupmgr.ui.StartupNormalAppListActivity");
        } catch (Exception e) {
            showActivity("com.huawei.systemmanager",
                    "com.huawei.systemmanager.optimize.bootstart.BootStartActivity");
        }
    }

    /**
     * 小米
     */
    public static boolean isXiaomi() {
        return Build.BRAND != null && Build.BRAND.toLowerCase().equals("xiaomi");
    }

    /**
     * 操作步骤：授权管理 -> 自启动管理 -> 允许应用自启动
     */
    private void goXiaomiSetting() {
        try {
            showActivity("com.miui.securitycenter",
                    "com.miui.permcenter.autostart.AutoStartManagementActivity");
        } catch (Exception e) {

        }
    }

    /**
     * OPPO
     */
    public static boolean isOPPO() {
        return Build.BRAND != null && Build.BRAND.toLowerCase().equals("oppo");
    }

    /**
     * 操作步骤：权限隐私 -> 自启动管理 -> 允许应用自启动
     */
    private void goOPPOSetting() {
        try {
            showActivity("com.coloros.phonemanager");
        } catch (Exception e1) {
            try {
                showActivity("com.oppo.safe");
            } catch (Exception e2) {
                try {
                    showActivity("com.coloros.oppoguardelf");
                } catch (Exception e3) {
                    showActivity("com.coloros.safecenter");
                }
            }
        }
    }

    /**
     * VIVO
     */
    public static boolean isVIVO() {
        return Build.BRAND != null && Build.BRAND.toLowerCase().equals("vivo");
    }

    /**
     * 操作步骤：权限管理 -> 自启动 -> 允许应用自启动
     */
    private void goVIVOSetting() {
        try {
            showActivity("com.iqoo.secure");
        } catch (Exception e) {

        }
    }

    /**
     * 魅族
     */
    public static boolean isMeizu() {
        return Build.BRAND != null && Build.BRAND.toLowerCase().equals("meizu");
    }

    /**
     * 操作步骤：权限管理 -> 后台管理 -> 点击应用 -> 允许后台运行
     */
    private void goMeizuSetting() {
        try {
            showActivity("com.meizu.safe");
        } catch (Exception e) {

        }
    }

    /**
     * 三星
     */
    public static boolean isSamsung() {
        return Build.BRAND != null && Build.BRAND.toLowerCase().equals("samsung");
    }

    /**
     * 操作步骤：自动运行应用程序 -> 打开应用开关 -> 电池管理 -> 未监视的应用程序 -> 添加应用
     */
    private void goSamsungSetting() {
        try {
            showActivity("com.samsung.android.sm_cn");
        } catch (Exception e) {
            showActivity("com.samsung.android.sm");
        }
    }

    /**
     * 乐视
     */
    public static boolean isLeTV() {
        return Build.BRAND != null && Build.BRAND.toLowerCase().equals("letv");
    }

    /**
     * 操作步骤：自启动管理 -> 允许应用自启动
     */
    private void goLetvSetting() {
        try {
            showActivity("com.letv.android.letvsafe",
                    "com.letv.android.letvsafe.AutobootManageActivity");
        } catch (Exception e) {

        }
    }

    /**
     * 锤子
     */
    public static boolean isSmartisan() {
        return Build.BRAND != null && Build.BRAND.toLowerCase().equals("smartisan");
    }

    /**
     * 操作步骤：权限管理 -> 自启动权限管理 -> 点击应用 -> 允许被系统启动
     */
    private void goSmartisanSetting() {
        try {
            showActivity("com.smartisanos.security");
        } catch (Exception e) {

        }
    }
}
